<template>
  <div id="app">
    <router-view v-if="isRouterAlive"></router-view>
  </div>
</template>
<script>
import util from '@/libs/util';
import { on, off } from 'view-design/src/utils/dom';
import { setMatchMedia } from 'view-design/src/utils/assist';
import { mapMutations, mapActions, mapGetters } from 'vuex';
import * as loginUtil from '@/libs/util.login';
import { loginUrl } from '@/constants';
import { login } from '@/api/login';
import { queryLoginUserInfoService } from '@/api/public';
import permissions from '@/mixins/permissions';
import Cookies from 'js-cookie';

setMatchMedia();

export default {
  name: 'app',
  mixins: [permissions],
  provide () { // 页面重载
    return {
      reloadPage: this.reloadPage
    }
  },
  data () {
    return {
      token: '',
      util: util,
      isRouterAlive: true // 显示router-view
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['getMenuSiderList'])
  },
  mounted () {
    on(window, 'resize', this.handleWindowResize);
    this.handleMatchMedia();
    this.loginFn();
    if (Cookies.get('uc_token')) {
      if (
        !sessionStorage.getItem('thirdMenuList') ||
        !sessionStorage.getItem('systematicBtns')
      ) {
        this.handleReloadData();
      }
    }
  },
  beforeDestroy () {
    off(window, 'resize', this.handleWindowResize);
  },
  methods: {
    ...mapMutations('admin/layout', ['setDevice']),
    ...mapMutations('admin/user', [
      'SET_USERINFO'
    ]),
    ...mapActions('permissions/systemBtns', ['getMenulist']),
    // 页面重载
    reloadPage () {
      this.isRouterAlive = false;
      this.$nextTick(() => {
        this.isRouterAlive = true;
      });
    },
    handleWindowResize () {
      this.handleMatchMedia();
    },
    handleMatchMedia () {
      const matchMedia = window.matchMedia;
      if (matchMedia('(max-width: 600px)').matches) {
        this.setDevice('Mobile');
      } else if (matchMedia('(max-width: 992px)').matches) {
        this.setDevice('Tablet');
      } else {
        this.setDevice('Desktop');
      }
    },
    handleReduceThirdMenuList (menulist) {
      return menulist.reduce((value, item) => {
        item.children.forEach((elem) => {
          // todo
          if (elem.children) {
            value.push(...elem.children);
          }
        });
        return value;
      }, []);
    },
    async handleReloadData () {
      const data = {
        channelId: 11,
        menuLevel: 1,
        parentMenuId: 0
      };
      await this.getMenulist({
        payload: {
          data
        }
      });
      let menulist = this.getMenuSiderList();
      this.$store.commit('admin/menu/setSider', menulist);
      let thirdMenuList = this.handleReduceThirdMenuList(menulist);
      sessionStorage.setItem('thirdMenuList', JSON.stringify(thirdMenuList));
      loginUtil.getAllBtnsList(); // 获取平台的全量菜单
    },
    async loginFn () {
      let mtk = loginUtil.getQueryString('m_tk');
      if (mtk) {
        let res = await login({}, mtk);
        if (res.code === '0') {
          this.queryLoginUserInfo()
        } else if (res.code === '-2004') {
          /* 已登录状态 刷新调用 保持登录不执行操作 */
          loginUtil.getAllBtnsList();
        } else {
          window.location.href = loginUrl; // 登录失败，重新跳转登录页
        }
      }
    },
    // 查询用户信息
    async queryLoginUserInfo () {
      const res = await queryLoginUserInfoService({})
      if (res) {
        this.SET_USERINFO(res.retData)
        localStorage.setItem('userInfo', JSON.stringify(res.retData));
        this.handleReloadData();
      }
    }
  }
};
</script>
<style scoped>
#app {
  overflow: hidden;
}
</style>
